package com.jinlejia.erp.ui.house;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.ActivityWriteFollowBinding;
import com.jinlejia.erp.ui.common.SheetSelect;
import com.jinlejia.erp.utils.DataFilter;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 房源跟进
 */
public class WriteFollowActivity extends AppCompatActivity {

    ArrayList<Map<String, Object>> typeList = new ArrayList<>();
    JSONObject jsonObject = new JSONObject();
    ArrayList<Map<String, Object>> reasonList = new ArrayList<>();

    private ActivityWriteFollowBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_write_follow);

        binding.btBack.setOnClickListener(this::onClick);
        binding.rlFollowType.setOnClickListener(this::onClick);
        binding.btSubmit.setOnClickListener(this::onClick);
        binding.rlFollowReason.setOnClickListener(this::onClick);


        getType();
        jsonObject.put("rscode", getIntent().getStringExtra("code"));
        binding.tvCode.setText(getIntent().getStringExtra("code"));



        binding.inputContent.addTextChangedListener(new TextWatcher() {
            private CharSequence temp;
            private int selectionStart;
            private int selectionEnd;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                temp = s;
            }

            @Override
            public void afterTextChanged(Editable s) {
                int number = 200 - s.length();
                binding.textCount.setText(number + "/200");
                selectionStart = binding.inputContent.getSelectionStart();
                selectionEnd = binding.inputContent.getSelectionEnd();
                if (temp.length() > 200) {
                    s.delete(selectionStart - 1, selectionEnd);
                    int tempSelection = selectionEnd;
                    binding.inputContent.setText(s);
                    binding.inputContent.setSelection(tempSelection);//设置光标在最后
                }
            }
        });

    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_back:
                finish();
                break;
            case R.id.rl_follow_type:
                final SheetSelect typeSelect = new SheetSelect(WriteFollowActivity.this, "跟进方式", typeList);
                typeSelect.show();
                typeSelect.setOnSelectListener(o -> {
                    Map<String, Object> map = (Map<String, Object>) o;
                    typeSelect.dismiss();
                    binding.followType.setText(map.get("valueName").toString());
                    jsonObject.put("followStyle", map.get("valuel").toString());
                });
                break;
            case R.id.bt_submit:
                jsonObject.put("followContent", binding.inputContent.getText().toString());
                if (jsonObject.containsKey("followStyle") && TextUtils.isEmpty(jsonObject.get("followStyle").toString())) {
                    CustomToast.showToast(this, "请选择跟进方式", 1500);
                } else if (!jsonObject.containsKey("followResult")) {
                    CustomToast.showToast(this, "请选择跟进结果", 1500);
                } else if (TextUtils.isEmpty(jsonObject.get("followContent").toString())) {
                    CustomToast.showToast(this, "请输入跟进内容", 1500);
                } else {
                    submit();
                }
                break;
            case R.id.rl_follow_reason:
                final SheetSelect reasonSelect = new SheetSelect(WriteFollowActivity.this, "跟进结果", reasonList);
                reasonSelect.show();
                reasonSelect.setOnSelectListener(o -> {
                    Map<String, Object> map = (Map<String, Object>) o;
                    reasonSelect.dismiss();
                    binding.followReason.setText(map.get("valueName").toString());
                    jsonObject.put("followResult", map.get("valuel").toString());
                    if (!map.get("valueName").toString().equals("接通") && !map.get("valueName").toString().equals("微信或其他")) {
                        binding.inputContent.setText(map.get("valueName").toString());
                    } else {
                        binding.inputContent.setText("");
                    }

                });
                break;
            default:
                break;
        }
    }

    private void getType() {
        String url;
        if (getIntent().getStringExtra("type").equals("shs")) {
            url = ApiConfig.SHS_FOLLOW_TYPE;
        } else {
            url = ApiConfig.RENT_FOLLOW_TYPE;
        }
        OkHttpUtils.get()
                .url(url.concat(getIntent().getStringExtra("code")))
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(WriteFollowActivity.this, response)) {
                            JSONObject data = JSON.parseObject(response.get("data").toString());
                            //数据列表
                            typeList = JSON.parseObject(data.getJSONObject("followReadyResult").getJSONArray("dictionaryList").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            reasonList = JSON.parseObject(data.getJSONObject("followReadyResult").getJSONArray("houseFollowResult").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });

                            binding.followReason.setText(reasonList.get(0).get("valueName").toString());
                            jsonObject.put("followResult", reasonList.get(0).get("valuel").toString());

                            binding.followType.setText(String.valueOf(typeList.get(0).get("valueName")));
                            jsonObject.put("followStyle", String.valueOf(typeList.get(0).get("valueName")));
                        }
                    }
                });
    }

    private void submit() {
        String url;
        if (getIntent().getStringExtra("type").equals("shs")) {
            url = ApiConfig.SHS_FOLLOW_SUBMIT;
        } else {
            url = ApiConfig.RENT_FOLLOW_SUBMIT;
        }
        OkHttpUtils.postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(WriteFollowActivity.this, response)) {
                            finish();
                        }
                    }
                });
    }
}
